/*
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2023-03-24 15:23:16
 */
const express = require('express')
const bodyParser = require('body-parser')
//导入token中间件jwt
const jwts = require('./dao/jwt')

const app = express()
const port = 3001

//socket.io
const { createServer } = require("http");
const { Server } = require('socket.io')
const httpServer = createServer(app);
const io = new Server(httpServer, {
    /* options */
});
//传入参数io
require('./dao/socket')(io);


httpServer.listen(8082);

//封装一个res.send的中间件函数，优化操作
app.use((req, res, next) => {
    res.sendMsg = function (err, code = 400, data = null) {
        res.send({
            code,
            message: err instanceof Error ? err.message : err,
            data
        })
    }
    next()
})

//处理post请求前端提交的数据  application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }))
//处理 application/json   限制最大请求数据
app.use(bodyParser.json({ limit: '50mb' }))

//获取静态路径 使用静态路径 托管静态资源，就可以让外界进行访问[对外提供资源访问时，目录名不会出现在URL中]
app.use(express.static(__dirname + '/uploads'))


//引入cors中间件解决跨越问题
const cors = require('cors')
app.use(cors())


//token判断
app.use(function (req, res, next) {
    if (typeof (req.headers.token) != 'undefined') {
        let token = req.headers.token
        let { verifytoken } = jwts.verifyToken(token)
        if (verifytoken == 1) {//token验证正确 
            //console.log('token验证成功');
            next()
        } else {
            console.log('token验证失败');
            res.sendMsg('token验证失败', 304)
        }
    } else {
        next()
    }
})

//引入路由组件
const groupRouter = require('./router/group')
app.use('/group', groupRouter)
const files = require('./router/files');
app.use('/files', files)
//引入聊天页面路由组件
const chatRouter = require('./router/chat')
app.use('/chat', chatRouter)
const router = require('./router/index')
app.use('/home', router)
//引入用户路由组件
const userRouter = require('./router/user')
app.use('/api', userRouter)
//引入搜索路由组件
const searchRouter = require('./router/search')
app.use('/search', searchRouter)
//引入用户详情组件
const userDetailRouter = require('./router/userDetail')
app.use('/user', userDetailRouter)
//引入添加好友组件
const addFriendRouter = require('./router/addfriend')
app.use('/add', addFriendRouter)

//404页面
app.use(function (req, res, next) {
    let err = new Error('404 Not Found')
    err.status = 404
    next(err)
})

//定义错误级别中间件  放在最后
app.use((err, req, res, next) => {
    res.status(err.status || 500)
    res.send(err.message)
})


app.listen(port, () => {
    console.log('你已经成功启动服务器!');
    console.log(`express server is running on  http://127.0.0.1:${port}`);
})